package com.jia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jia.entity.ChatFriend;
import com.jia.entity.ChatFriendApply;
import com.jia.entity.SysUser;
import com.jia.mapper.ChatFriendApplyMapper;
import com.jia.mapper.ChatFriendMapper;
import com.jia.mapper.SysUserMapper;
import com.jia.service.ChatFriendApplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 杜佳佳
 * @since 2021-05-30
 */
@Service
public class ChatFriendApplyServiceImpl extends ServiceImpl<ChatFriendApplyMapper, ChatFriendApply> implements ChatFriendApplyService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ChatFriendMapper chatFriendMapper;

    @Override
    public List<SysUser> getListByUserId(String userId) {

        QueryWrapper<ChatFriendApply> wrapper = new QueryWrapper<>();
        wrapper.eq("to_id",userId).eq("status",0);
        List<ChatFriendApply> chatFriendApplies = baseMapper.selectList(wrapper);
        List<SysUser> list = new ArrayList<>();
        if (chatFriendApplies.size() >0) {
            chatFriendApplies.forEach(item -> {
                SysUser sysUser = sysUserMapper.selectById(item.getFromId());
                list.add(sysUser);
            });
        }

        return list;
    }

    @Transactional
    @Override
    public void agree(String fromId, String toId) {
        QueryWrapper<ChatFriendApply> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("from_id",fromId).eq("to_id",toId);
        ChatFriendApply chatFriendApply = baseMapper.selectOne(wrapper1);
        chatFriendApply.setStatus(1);
        baseMapper.updateById(chatFriendApply);

        ChatFriend chatFriend1 = new ChatFriend();
        chatFriend1.setUserId(toId);
        chatFriend1.setFriendId(fromId);
        chatFriend1.setRemark(sysUserMapper.selectById(fromId).getNickname());
        chatFriendMapper.insert(chatFriend1);

        ChatFriend chatFriend2 = new ChatFriend();
        chatFriend2.setUserId(fromId);
        chatFriend2.setFriendId(toId);
        chatFriend2.setRemark(sysUserMapper.selectById(toId).getNickname());
        chatFriendMapper.insert(chatFriend2);
    }

    @Override
    public void reject(String fromId, String toId) {
        QueryWrapper<ChatFriendApply> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("from_id",fromId).eq("to_id",toId);
        ChatFriendApply chatFriendApply = baseMapper.selectOne(wrapper1);
        chatFriendApply.setStatus(2);
        baseMapper.updateById(chatFriendApply);
    }
}
